package edu.upc.fib.lamsandroid.client;

import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import edu.upc.fib.lamsandroid.server.api.model.Lesson;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;


public class LamsAndroidClientApplication extends Application {

    private static LamsAndroidClientApplication instance;

    public static LamsAndroidClientApplication getInstance() {
        return instance;
    }

    private HttpClient httpclient;
    private CookieStore cookieStore;
    private HttpContext localContext;
    private Lesson currentLesson;

    private boolean logoutRequested;

    @Override
    public void onCreate() {
        cookieStore = new BasicCookieStore();
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        httpclient = new DefaultHttpClient();

        instance = this;
    }

    @Override
    public void onTerminate() {

    }

    public HttpResponse doPost(HttpPost httppost) throws IOException {
        return httpclient.execute(httppost, localContext);
    }

    public void resetPreferences() {
        PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
        PreferenceManager.setDefaultValues(this,R.xml.prefs_connection, true);

    }

    public SharedPreferences getPreferences() {
        return PreferenceManager.getDefaultSharedPreferences(this);
    }

    public void setCurrentLesson(Lesson lesson) {
        currentLesson = lesson;
    }

    public Lesson getCurrentLesson() {
        return currentLesson;
    }

    public String getFileRequestURLPrefix() {
        String host = getPreferences().getString("host_preference", "");
        int port = Integer.parseInt(getPreferences().getString("port_preference", "0"));
        String context = getPreferences().getString("context_preference", "");

        return "http://" + host + ":" + port + "/" + context + "/activity/getFileByNodeId/";
    }

    public boolean isLogoutRequested() {
        return logoutRequested;
    }

    public void setLogoutRequested(boolean logoutRequested) {
        this.logoutRequested = logoutRequested;
    }
}
